package cn.finder0519.simplemediaplayer;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_POST_NOTIFICATIONS = 1001;

    private ActivityResultLauncher<Intent> pickMediaLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestNotificationPermissionIfNeeded();

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, android.R.color.transparent)));
        }

        Button selectLocalMediaFileButton = findViewById(R.id.btn_select_local_media_file);
        selectLocalMediaFileButton.setOnClickListener(v -> openLocalMediaFileSelector());
        pickMediaLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                if (data != null) {
                    Uri uri = data.getData();
                    startPlayerActivity(uri);
                }
            }
        });

        Button onlineMediaButton = findViewById(R.id.btn_online_media);
        onlineMediaButton.setOnClickListener(v -> openOnlineMedia());

    }

    private void requestNotificationPermissionIfNeeded() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_CODE_POST_NOTIFICATIONS
                );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_POST_NOTIFICATIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, getString(R.string.notification_granted), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.notification_not_granted), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.about) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.about));
            PackageManager pm = getPackageManager();
            PackageInfo pi;
            try {
                pi = pm.getPackageInfo(getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(e);
            }
            String versionName = pi.versionName;
            builder.setMessage(getString(R.string.version) + versionName);
            builder.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void openLocalMediaFileSelector() {
        // 启动文件选择器（SAF）
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*"); // 设置为 */* 并配合 EXTRA_MIME_TYPES 指定具体类型

        String[] mimeTypes = {"video/*", "audio/*"};

        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        pickMediaLauncher.launch(intent);

    }

    private void openOnlineMedia() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.enter_online_link));
        EditText input = new EditText(this);
        input.setHint(getString(R.string.url_hint));
        String savedUrl = getSharedPreferences("app", MODE_PRIVATE)
                .getString("savedUrl", null);
        input.setText(savedUrl);
        builder.setView(input);
        builder.setPositiveButton(getString(R.string.play), (dialog, which) -> {
            String url = input.getText().toString();
            if (!url.isEmpty() && (url.startsWith("http://")
                    || url.startsWith("https://")
                    || url.startsWith("rtmp://")
                    || url.startsWith("rtsp://"))) {
                Uri uri = Uri.parse(url);
                startPlayerActivity(uri);
            } else {
                Toast.makeText(this, getString(R.string.invalid_link), Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void startPlayerActivity(Uri mediaUri) {
        // 启动 PlayerActivity 并传递 URI
        Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
        intent.setData(mediaUri);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

}
